<?php
/**
* Copyright 2009 Waag Society <http://www.waag.org>
* This file is part of Annotrax.
*
* Annotrax is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Annotrax is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Annotrax.
* If not, see http://www.gnu.org/licenses/gpl.html
*/
class Default_Model_DomainMapper extends At_Model_Mapper{
    protected $dbTable;
    protected $tableName = 'keyword';

	/**
	 * Fetch domain from DB by name if it exists
	 *
	 * @param Default_Model_Domain $domain domain. Assumes $name is set!
	 * @return void
	 */
	public function findByName( Default_Model_Domain $domain ){
		$db 	= $this->getTable()->getAdapter();
		$value  = $db->fetchRow( 'SELECT * FROM domain WHERE name = ?', $domain->name );

		if( key_exists( 'id', $value ) ){
			foreach( $value as $key => $name ){
				$domain->$key = $name;
			}
		}
	}

	/**
	 * Save domain. updates if id is set, inserts and sets id otherwise
	 *
	 * @param Default_Model_Domain $domain Domain to save
	 * @return void
	 */
	public function save( Default_Model_Domain $domain ){
		$values = array(
			'name'		  => $domain->name,
			'description' => $domain->description
		);

		if( null == $domain->id ){
			$domain->id = $this->getTable()->insert( $values );
		}
		else{
			$this->getTable()->update( $values, array( 'id =?' => $keyword->id ) );
			foreach( $values as $key => $value ){
				//assert that that the values are set the where // find may overwrite them
				$domain->$key = $value;
			}
		}
	}

	/**
	 * Fetch all domains
	 *
	 * @return array $domains
	 */
	public function fetchAll(){
		$db = $this->getTable()->getAdapter();

		$results = $db->fetchAll('SELECT * FROM domain');

		foreach( $results as $index => $object ){
			$results[$index] = new Default_Model_Domain( $object );
		}

		return $results;
	}
}
